import { Request, Response, NextFunction } from 'express'
import { getPlayers, getPlayerById, createPlayer, updatePlayer, deletePlayer } from '../services/playerService'
import { validateCreatePlayerRequest, validateUpdatePlayerRequest, validatePagination, validateSort, createValidationError } from '../utils/validation'
import { ApiResponse, PaginatedResponse } from '../types/api'
import { sendError, AppError } from '../utils/errors'

// 获取选手列表
export const getPlayerList = async (req: Request, res: Response, next: NextFunction) => {
  try {
    const { keyword, rank, position, sortBy, sortOrder } = req.query
    const { page, pageSize } = validatePagination(
      parseInt(req.query.page as string),
      parseInt(req.query.pageSize as string)
    )
    const { sortBy: validatedSortBy, sortOrder: validatedSortOrder } = validateSort(
      sortBy as string,
      sortOrder as string
    )

    const result = await getPlayers({
      page,
      pageSize,
      keyword: keyword as string,
      rank: rank as string,
      position: position as string,
      sortBy: validatedSortBy as any,
      sortOrder: validatedSortOrder
    })

    const response: PaginatedResponse<any> = {
      success: true,
      data: result,
      message: '查询成功'
    }

    res.json(response)
  } catch (error) {
    if (error instanceof AppError) {
      sendError(res, error)
    } else {
      next(error)
    }
  }
}

// 获取选手详情
export const getPlayerDetail = async (req: Request, res: Response, next: NextFunction) => {
  try {
    const { id } = req.params
    if (!id) {
      throw createValidationError('选手ID不能为空')
    }
    const player = await getPlayerById(id)

    const response: ApiResponse = {
      success: true,
      data: player,
      message: '查询成功'
    }

    res.json(response)
  } catch (error) {
    if (error instanceof AppError) {
      sendError(res, error)
    } else {
      next(error)
    }
  }
}

// 创建选手
export const createPlayerHandler = async (req: Request, res: Response, next: NextFunction) => {
  try {
    validateCreatePlayerRequest(req.body)
    const player = await createPlayer(req.body)

    const response: ApiResponse = {
      success: true,
      data: player,
      message: '选手创建成功'
    }

    res.status(201).json(response)
  } catch (error) {
    if (error instanceof AppError) {
      sendError(res, error)
    } else {
      next(error)
    }
  }
}

// 更新选手
export const updatePlayerHandler = async (req: Request, res: Response, next: NextFunction) => {
  try {
    const { id } = req.params
    if (!id) {
      throw createValidationError('选手ID不能为空')
    }
    validateUpdatePlayerRequest(req.body)
    const player = await updatePlayer(id, req.body)

    const response: ApiResponse = {
      success: true,
      data: player,
      message: '选手信息更新成功'
    }

    res.json(response)
  } catch (error) {
    if (error instanceof AppError) {
      sendError(res, error)
    } else {
      next(error)
    }
  }
}

// 删除选手
export const deletePlayerHandler = async (req: Request, res: Response, next: NextFunction) => {
  try {
    const { id } = req.params
    if (!id) {
      throw createValidationError('选手ID不能为空')
    }
    await deletePlayer(id)

    const response: ApiResponse = {
      success: true,
      data: null,
      message: '选手删除成功'
    }

    res.json(response)
  } catch (error) {
    if (error instanceof AppError) {
      sendError(res, error)
    } else {
      next(error)
    }
  }
}

// 获取所有选手（不分页，用于分组页面）
export const getAllPlayersForGrouping = async (_req: Request, res: Response, next: NextFunction) => {
  try {
    const { prisma } = await import('../utils/database')
    
    const players = await prisma.player.findMany({
      orderBy: {
        createdAt: 'desc'
      }
    })

    // 获取每个选手的位置信息
    const playersWithPositions = await Promise.all(
      players.map(async (player) => {
        const positionMappings = await prisma.playerPositionMapping.findMany({
          where: { playerId: player.id },
          select: { position: true }
        })
        const positions = positionMappings.map(p => p.position)
        
        return {
          id: player.id,
          nickname: player.nickname,
          rank: player.rank,
          highestMmr: player.highestMmr,
          ability: player.ability,
          tags: player.tags ? JSON.parse(player.tags) : [],
          createdAt: player.createdAt.toISOString(),
          updatedAt: player.updatedAt.toISOString(),
          positions: positions
        }
      })
    )

    const response: ApiResponse = {
      success: true,
      data: playersWithPositions,
      message: '查询成功'
    }

    res.json(response)
  } catch (error) {
    if (error instanceof AppError) {
      sendError(res, error)
    } else {
      next(error)
    }
  }
}
